﻿using System;
using System.Management;
using System.Windows.Forms;

namespace WMItest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Info();
        }

        public void Info()
        {
            // 构造查询字符串
            string query = "SELECT * FROM Win32_SerialPort";

            // 创建ManagementObjectSearcher对象，用于执行WMI查询
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            // 执行查询，获取Win32_SerialPort对象集合
            ManagementObjectCollection serialPorts = searcher.Get();

            // 遍历每个Win32_SerialPort对象
            foreach (ManagementObject serialPort in serialPorts)
            {
                var PNPDeviceID = GetSerialProp(serialPort,"PNPDeviceID");
                var DeviceId = GetSerialProp(serialPort, "DeviceId");
                var Name = GetSerialProp(serialPort, "Name");
                var Description = GetSerialProp(serialPort, "Description");
                var Status = GetSerialProp(serialPort, "Status");
                var Service = GetSerialProp(serialPort, "Service");
                var ClassGuid = GetSerialProp(serialPort, "ClassGuid");
            }
        }

        private object GetSerialProp(ManagementObject serialPort,string prop)
        {
            try
            {
                return serialPort[prop];
            }
            catch (ManagementException e)
            {
                Console.WriteLine("Error: " + e.Message);
                return null;
            }
        }
    }

}
